﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi;
using System.Text;

namespace OpenApiExtensions
{
    public static class OpenApiExtensions
    {
        public static IServiceCollection AddOpenApiService(this IServiceCollection services, IConfigurationSection section)
        {
            services.Configure<OpenApiConfig>(section);
            var config = section.Get<OpenApiConfig>() ?? new OpenApiConfig();
            if (!config.Enable) return services;
            if (config != null && config.Docs != null)
            {
                foreach (var doc in config.Docs)
                {
                    services.AddOpenApi(doc.GroupName, options =>
                    {
                        options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0;
                        options.ShouldInclude = (a) =>
                        {
                            if (a.GroupName == doc.GroupName) return true;

                            return false;
                        };
                        options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
                        options.AddSchemaTransformer<FixEnumSchemaTransformer>();
                        options.AddSchemaTransformer<FixNullbleSchemaTransformer>();
                        options.AddSchemaTransformer<DefaultValueSchemaTransformer>();

                    });
                }
            }
            return services;
        }

        /// <summary>
        /// 使用OPENAPI
        /// </summary>
        /// <param name="app"></param>
        public static void UseOpenApiUI(this WebApplication app)
        {

            var config = app.Configuration.GetSection("OpenApi").Get<OpenApiConfig>() ?? new OpenApiConfig();

            if (!config.Enable) return;
            app.MapOpenApi();
            const string CustomStyles = @"
             .swagger-ui .opblock .opblock-summary .view-line-link {
                 margin: 0 5px;
                 width: 24px;
             }";




            app.MapGet($"/{config.RoutePrefix}/custom.css", [ApiExplorerSettings(IgnoreApi = true)] () => Results.Text(CustomStyles, "text/css", Encoding.UTF8)).ExcludeFromDescription();

            app.UseSwaggerUI(options =>
            {
                options.RoutePrefix = config.RoutePrefix;
                options.InjectStylesheet($"/{config.RoutePrefix}/custom.css");

                if (config.Docs != null)
                {
                    foreach (var doc in config.Docs)
                    {
                        options.SwaggerEndpoint($"/openapi/{doc.GroupName}.json", doc.GroupName);
                    }
                }
                options.DocExpansion(config.DocExpansion);//折叠Api
                options.DocumentTitle = config.DocumentTitle;
            });


        }

    }
}
